package com.snda.lib.task;

import java.util.HashMap;
import java.util.Map;

import com.snda.lib.http.FileCache;
import com.snda.lib.http.HttpUtil;
import com.snda.lib.http.ICallBack;
import android.content.Context;
import android.util.Log;

// 所有Http Get请求的基类
public class HttpGetTask extends HttpAnsycTask {

	public HttpGetTask(Context context, ICallBack callback) {
		super(context, callback);
	}

	@Override
	protected Map<String, Object> doHttpRequest() {

		// 首先检查该网址对应的文件缓存是否存在，如果存在则直接读取
		if (bCached == true && bForceRefresh == false) {
			String url = httpRequest.getRequestUrl(strUrl);

			String strResponse = FileCache.getFromCache(context, url);
			if (strResponse != null && strResponse.equals("") == false) {
				int nIndex = strResponse.indexOf(':');
				if (nIndex != -1) {
					String strCachedTime = strResponse.substring(0, nIndex);
					Long lCacheTime = Long.parseLong(strCachedTime);

					strResponse = strResponse.substring(nIndex + 1);

					// 尚未过期，则使用未过期的缓存
					if (System.currentTimeMillis() - lCacheTime <= this.nCacheTime * 1000) {
						Map<String, Object> mapData = new HashMap<String, Object>();
						mapData.put(HttpUtil.KEY_ERROR_CODE,
								HttpUtil.ERROR_SUCCESS);
						mapData.put(HttpUtil.KEY_CONTENT, strResponse);

						Log.d("TYLib", "load response from cache success:");
						Log.d("TYLib", strResponse);
						return mapData;
					}
				}
			}
		}

		Map<String, Object> mapData = httpRequest.doGetRequest(strUrl);

		// 如果是强制刷新，则没有必要缓存
		if (bCached == true && mapData != null) {
			String strResponse = (String) mapData.get(HttpUtil.KEY_CONTENT);
			if (strResponse != null && strResponse.equals("") == false) {

				String strCurrentTime = String.valueOf(System
						.currentTimeMillis());
				String url = httpRequest.getRequestUrl(strUrl);
				boolean bSuccess = FileCache.saveToCache(context, url,
						strCurrentTime + ":" + strResponse);
				if (bSuccess == true) {
					Log.d("TYLib", "save response into cache success:");
					Log.d("TYLib", strResponse);
				}
			}
		}

		return mapData;
	}

	// Get请求类重载
	protected Map<String, Object> parseResponse(String strResponse) {
		return null;
	}

	protected Map<String, Object> process(Map<String, Object> mapData) {

		mapData = checkResponse(mapData);
		if (mapData == null)
			return null;

		Integer nError = (Integer) mapData.get(HttpUtil.KEY_ERROR_CODE);
		if (nError != HttpUtil.ERROR_SUCCESS)
			return mapData;

		String strResponse = (String) mapData.get(HttpUtil.KEY_CONTENT);
		return parseResponse(strResponse);
	}
}